#!c:/Python27/python.exe -u
# -*- coding: utf-8/IGNORE',$string);-*-
''' Tema - Linguagens de Programação Dinâmicas
Trabalho de Python á Discíplina - Linguagens de Programação

Reports.py tem como função gerar um relatório em PDF com as estatisticas pedidas
Depois de efectuar a ligação a Base de dados, realiza a leitura dos mesmos passandos por filtros e inserindo na folha pdf
A cada função da classe, possui filtros que retornam graficos e tabelas com os dados estatisticos pedidos
'''
__author__ = "Miguel Fialho, Nº 5958 - Pedro Serrano, Nº 3958"
__copyright__ = "Copyright 2014 - Miguel Fialho / Pedro Serrano"
__credits__ = ""
__license__ = "GPL"
__maintainer__ = "1.0"
__email__ = "mF200_5@hotmail.com"
__status__ = ""

'''Importações de bibliotecas e módulos para o desenvolvimento de funções aritméticas, gráficas, lógicas, entre outras...'''
import os
import time
from reportlab.rl_config import *
import numpy as np
from Statistics import*
import ReadFile
from ReadFile import *
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.orm import sessionmaker
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle, TA_CENTER,black, white 
from reportlab.lib.units import inch, mm
from reportlab.lib import colors
from reportlab.lib.colors import *
from reportlab.lib.pagesizes import A4
from reportlab.lib.pagesizes import letter
from reportlab.lib.validators import Auto, _isColor
from reportlab.lib.enums import TA_LEFT, TA_RIGHT, TA_CENTER, TA_JUSTIFY
from reportlab.lib.extformat import magicformat
from reportlab.platypus import Paragraph, Frame, Spacer, Image, Table, TableStyle, SimpleDocTemplate, PageBreak
from reportlab.graphics.charts.barcharts import VerticalBarChart
from reportlab.graphics.shapes import Drawing, String
from reportlab.graphics.charts.textlabels import Label
from reportlab.graphics.charts.legends import Legend, TotalAnnotator
from reportlab.graphics.charts.linecharts import HorizontalLineChart
from reportlab.graphics.charts.barcharts import VerticalBarChart 
from reportlab.graphics.charts.axes import XCategoryAxis,YValueAxis
from reportlab.graphics.charts.lineplots import AreaLinePlot 
from reportlab.graphics.charts.doughnut import Doughnut
from reportlab.graphics.shapes import Drawing, _DrawingEditorMixin, String, Rect, Line, Group
from reportlab.graphics.widgets.markers import makeMarker
from reportlab.graphics.charts.piecharts import Pie  
from reportlab.graphics.charts.textlabels import Label  
from reportlab.graphics.widgetbase import Widget, ScaleWidget
from reportlab.graphics.widgets.markers import Marker

class Reports():
    '''
    Classe responsável por criar relatórios em PDF com simplificação dos dados estatisticos e representação gráfica dos mesmos 
    '''
    def __init__(self):
        '''
        Instanciação e Inicialização da criação de sessão à base de dados
        '''
        AccoesBD.database = create_engine('sqlite:///DataBase.db', echo = False)
        AccoesBD.login = sessionmaker(bind=AccoesBD.database)
        AccoesBD.login.configure(bind=AccoesBD.database)
        AccoesBD.login = AccoesBD.login()
        pass

Ipc_globaList = list()
anos = list()
for i in range (1, 38):
    if os.path.isfile("DataBase.db") == True:
        Ipc_globaList.insert( i ,Statistics().getIpc_global(i))
        anos.insert( i ,Statistics().getAno(i))
        pass
    pass

label_IPC = 'Índice de Preços ao Consumidor'
label_Anos = 'Ano Transacto'
inscritosInt = Ipc_globaList
inscritosIn = [int(i) for i in inscritosInt]
results1 = inscritosIn
results2 = anos

def dataToParagraph(name, data):
    '''
    Função para Colocar os Label´s das estatisticas pedidas na Folha PDF
    '''
    p = '<strong>Dados Estatisticos: </strong>' + name + '<br/>' + '<strong>Data: </strong>  ('
    for i in range(len(data)):
        p += str(data[i])
        if i != len(data) - 1:
            p += ', '
        else:
            p += ')'   
    return p


def dataToTable(name, data):
   '''
   Função para converter os dados para a tabela
   '''
   data = [str(x) for x in data]
   data.insert(0,name)
   return data

def myPieChart(data):
    '''
    Função para criar gráfico de Pizza 
    '''
    drawingPie = Drawing(400, 200)
    pie = Pie()
    pie.x = 65
    pie.y = 15
    pie.width = 170
    pie.height = 170
    pie.data = data
    pie.labels = ['1977','1978','1979','1980','1981','1982','1983','1984','1985','1986','1987','1988','1989','1990','1991','1991','1993','1994',
    '1995','1996','1997','1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013']
    pie.slices.strokeWidth=0.5
    pie.slices.popout = 10 
    pie.sideLabels = 1

    drawingPie.add(pie)
    return drawingPie

def myGraphLinear(data):
    '''
    Função para criar gráfico Linear
    '''
    drawingGraphLinear = Drawing(400, 220)
    lc = HorizontalLineChart()
    lc.x = 30
    lc.y = 50
    lc.height = 125
    lc.width = 350
    lc.data = [data]
    lc.categoryAxis.categoryNames = ['1977','1978','1979','1980','1981','1982','1983','1984','1985','1986','1987','1988','1989','1990','1991','1991','1993','1994',
    '1995','1996','1997','1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013']
    lc.categoryAxis.labels.dx = -5
    lc.categoryAxis.labels.dy = -20
    lc.categoryAxis.labels.angle = 90
    lc.valueAxis.valueMin = 0
    lc.valueAxis.valueMax = 2000
    lc.valueAxis.subGridStrokeWidth = 0.25
    lc.valueAxis.visibleGrid = 1
    lc.lines.symbol = makeMarker('FilledCircle')
    lc.lines.strokeWidth = 1
    drawingGraphLinear.add(lc)

    return drawingGraphLinear

def myBarChart(data):
    '''
    Função para criar gráfico de Barras 
    '''
    drawing = Drawing(400, 200)
    bar = VerticalBarChart()
    bar.data = data
    bar.categoryAxis.categoryNames = ['1977','1978','1979','1980','1981','1982','1983','1984','1985','1986','1987','1988','1989','1990','1991','1991','1993','1994',
    '1995','1996','1997','1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013']  
    bar.categoryAxis.labels.fillColor = black 
    bar.categoryAxis.labels.dx = -5
    bar.categoryAxis.labels.dy = -15
    bar.categoryAxis.labels.angle = 90
    bar.valueAxis.subGridStrokeWidth = 0.25
    bar.valueAxis.visibleGrid = 1
    bar.width                      = 200  
    bar.height                     = 150  
    bar.x                          = 50 
    bar.y                          = 15  
    bar.barSpacing                 = 5  
    bar.groupSpacing               = 5  
    bar.valueAxis.labels.fontName  = 'Helvetica'  
    bar.valueAxis.labels.fontSize  = 5  
    bar.valueAxis.forceZero        = 1  
    bar.valueAxis.rangeRound       = 'both'  
    bar.valueAxis.valueMax         = None#10#  
    bar.categoryAxis.visible       = 1  
    bar.categoryAxis.visibleTicks  = 1  
    bar.strokeWidth                = 0.1  
    bar.bars.strokeWidth           = 0.5

    drawing.add(bar)
    return drawing

def myBarLegend(drawing, name1):

    d = drawing or Drawing(400, 500)
    swatches = Legend()
    swatches.alignment = 'right'
    swatches.x = 260
    swatches.y = 155
    swatches.deltax = 60
    swatches.dxTextSpace = 10
    swatches.columnMaximum = 4
    items = [(colors.red, name1)]
    swatches.colorNamePairs = items
    d.add(swatches, 'legend')
    return d

def myBarChart3D(data):

    drawing3D = Drawing(400, 200)
    dn = Doughnut()
    dn.x = 50
    dn.y = 10
    dn.width = 170
    dn.height =100
    dn.data = data
    dn.labels = ['1977','1978','1979','1980','1981','1982','1983','1984','1985','1986','1987','1988','1989','1990','1991','1991','1993','1994',
    '1995','1996','1997','1998','1999','2000','2001','2002','2003','2004','2005','2006','2007','2008','2009','2010','2011','2012','2013']
    dn.slices.strokeWidth=0.5
    dn.slices[3].popout = 10
    dn.slices[3].strokeWidth = 2
    dn.slices[3].strokeDashArray = [2,2]
    dn.slices[3].labelRadius = 1.75
    dn.slices[3].fontColor = colors.red
    dn.slices[0].fillColor = colors.darkcyan
    dn.slices[1].fillColor = colors.blueviolet
    dn.slices[2].fillColor = colors.blue
    dn.slices[3].fillColor = colors.cyan
    dn.slices[4].fillColor = colors.aquamarine
    dn.slices[5].fillColor = colors.cadetblue
    dn.slices[6].fillColor = colors.lightcoral 
    drawing3D.add(dn)

    drawing3D.add(dn)
    return drawing3D

def pdf(self):
    '''
    Função para criar o relatório PDF 
    '''
    story = []
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    story.append(Spacer(1,.25*inch))
    im = Image("images/estig_logo.png", width=2*inch, height=1*inch)
    im.hAlign = 'LEFT'
    story.append(im)

    story.append(Spacer(1,.40*inch))
    story.append(Paragraph('<font size=16>Evolução dos Salários</font>', styles["Center"]))
    story.append(Spacer(1,.15*inch))
    story.append(Paragraph('<font size=16>da Função Pública em Portugal</font>', styles["Center"]))
    story.append(Spacer(1,.25*inch))
    story.append(Paragraph('<font size=14>Trabalho Prático</font>', styles["Center"]))
    story.append(Spacer(0.1*inch,.10*inch))
    story.append(Paragraph('<font size=14>Linguagens de Programação</font>', styles["Center"]))
    story.append(Spacer(0.1*inch,.15*inch))

    timeStr = '<font size=12>{time}</font>'.format(time = time.ctime())
    story.append(Paragraph(timeStr, styles["Center"]))
    story.append(Spacer(0.1*inch, 1.3*inch))
    story.append(Paragraph('<font size=16>Análise Estatística dos Salários Portugueses</font>', styles["Center"]))
    story.append(Spacer(0.1*inch, 0.5*inch))

    im = Image("images/graficoPDF.jpg", width=3*inch, height=2*inch)
    im.hAlign = 'CENTER'
    story.append(im)
    story.append(Spacer(0.1*inch, 0.15*inch))

    story.append(Paragraph("Autor.: Miguel Fialho Nº 5958<br />Autor.: Pedro Serrano Nº 3958", styles["Normal"]))
    story.append(Spacer(0.1*inch, .25*inch))

    text = """ Relatório Estatistico sobre a evolução dos salários da função pública em Porugal, num inetrvalo
    de tempo entre 1977 a 2013, analisando assim as variáveis de: Indice de Preços ao consumidor, a Taxa de Inflação, 
    Remunerações Minima/Máxima mensal dos funcionários públicos, Pib, Rendimento Nacional/Disponivel bruto per capita
    """
    story.append(Paragraph(text, styles["Normal"]))
    story.append(Spacer(0.1*inch, .30*inch))
    
    img = Image("images/logotiposEuropa.jpg", width=3*inch, height=1*inch)
    img.hAlign = 'CENTER'
    story.append(img)
    story.append(Spacer(1,.20*inch))

    story.append(Paragraph('<font size=14>__________________________________________________________</font>', styles["Center"]))
    story.append(Spacer(0.1*inch, 0.3*inch))

    story.append(Paragraph('<font size=12>Processamento Estatistico: Informação Numérica</font>', styles["Normal"]))
    story.append(Spacer(0.1*inch, 0.2*inch))
    story.append(Paragraph(dataToParagraph(label_IPC, results1),styleN))
    story.append(Spacer(1,.20*inch))
    story.append(Paragraph(dataToParagraph(label_Anos, results2),styleN))
    story.append(Spacer(1,.2*inch))

    text_data = ["Ano", "IPC"]
    d = []
    font_size = 8
    centered = ParagraphStyle(name="centered", alignment=TA_CENTER)
    for text in text_data:
        ptext = "<font size=%s><b>%s</b></font>" % (font_size, text)
        p = Paragraph(ptext, centered)
        d.append(p)
        data = [d]
        line_num = 1
        formatted_line_data = []
        for x in range(1):
            line_data = [results2, results1]
            for item in line_data:
                ptext = "<font size=%s>%s</font>" % (font_size-1, item)
                p = Paragraph(ptext, centered)
                formatted_line_data.append(p)
            data.append(formatted_line_data)
            formatted_line_data = []

        GRID_STYLE = TableStyle([('GRID', (0,0), (-1,-1), 0.25, colors.black),('ALIGN', (1,1), (-1,-1), 'RIGHT')])
    table = Table(data, colWidths=[40, 40])
    table.setStyle(GRID_STYLE)
    story.append(table)
    story.append(Spacer(0.1*inch, 0.4*inch))
    story.append(Paragraph('<font size=14>__________________________________________________________</font>', styles["Center"]))
    story.append(Spacer(0.1*inch, 0.3*inch))

    story.append(Paragraph('<font size=14>__________________________________________________________</font>', styles["Center"]))
    story.append(Spacer(0.1*inch, 0.3*inch))

    story.append(Paragraph('<font size=12>Processamento Estatistico: Informação Gráfica</font>', styles["Normal"]))
    story.append(Spacer(0.1*inch, 0.2*inch))

    drawing = myBarChart([results1])
    drawing = myBarLegend(drawing,label_IPC)
    drawing.hAlign = 'CENTER'
    story.append(drawing)
    story.append(Spacer(1,1*inch))

    drawingPie = myPieChart(results1)
    drawingPie.hAlign = 'CENTER'
    story.append(drawingPie)

    drawingGraphLinear = myGraphLinear(results1)
    drawingGraphLinear.hAlign = 'CENTER'
    story.append(drawingGraphLinear)


    drawing3D = myBarChart3D(results1)
    drawing3D.hAlign = 'CENTER'
    drawing3D.renderScale = 1
    story.append(drawing3D)

    doc = SimpleDocTemplate('Relatorios/Indice de Precos ao consumidor (IPC).pdf',pagesize = letter, topMargin=0)
    tkMessageBox.showinfo("Relátorio IPC","Gravado com Sucesso!")
    doc.build(story)
    pass